﻿/*
 * DATAFLOWCORE
 * 
Copyright 2012 - Mindstorm Multitouch Limited

Author - Bertrand Nouvel

DataFlowCore is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

DataFlowCore is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser Public License for more details.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using MongoDB.Bson;

namespace DFlow
{

    public abstract class PersistentNode : Node
    {
        public class Parameters
        {
            public bool persistent;      // <- shall we try to 
            public string storageurl;    // <- where the model is meant to be stored            
        }

        protected bool updated = false;
        protected object persistent_data;

        public override void UpdateParameters(object co)
        {
            base.UpdateParameters(co);
            // try to load indicated model



        }

        public virtual bool IsUpdated()
        {
            return updated;
        }
        public virtual void SaveModel()
        {
            Parameters p = GetParameters() as Parameters;
            byte[] b = DFlowCore.BsonUtils.Encode(DFlowCore.BsonUtils.BsonEncode(persistent_data, null));
            (new FileStream(p.storageurl, FileMode.CreateNew)).Write(b, 0, b.Length);

        }

        public virtual void LoadModel(Type t)
        {
            Parameters p = GetParameters() as Parameters;
            long nbytes = (new System.IO.FileInfo(p.storageurl)).Length;
            byte[] b = new byte[nbytes];
            (new FileStream(p.storageurl, FileMode.Open)).Read(b, 0, (int)nbytes);
            persistent_data = DFlowCore.BsonUtils.BsonDecode(DFlowCore.BsonUtils.Decode(b), t);
        }

        public override void Dispose()
        {

            if (IsUpdated())
            {
                SaveModel();
            }

            base.Dispose();
        }
    }

}
